// pages/address/address.js
import { reqAddressListByuserid,DeleteByaddressid } from '../../api/address';

Page({
  data: {
    addressList: [], // 收货地址列表
    distance:'',//距离
    duration:'',//时间
    mi:''
  },
  //接受信息或返回
  goback(e){
   console.log(e);
   const eventChannel = this.getOpenerEventChannel();
      eventChannel.emit('backEvent', {
        obj:e.currentTarget.dataset.address
      })
    wx.navigateBack();
  },
  onLoad: function(options) {
      // 
    // 页面加载时获取收货地址列表
    this.getAddressList();
  },

  onShow: function() {
    // 监听页面显示事件，重新获取地址列表
    const eventChannel = this.getOpenerEventChannel();
    this.getAddressList();
    eventChannel.on('refreshAddressList', this.getAddressList.bind(this));
  },

  // 获取收货地址列表
  getAddressList: function() {
    // 从本地存储中获取用户信息
    const userInfo = wx.getStorageSync('userinfo');
    if (!userInfo || !userInfo.userid) {
      wx.showToast({
        title: '未获取到用户信息',
        icon: 'none'
      });
      return;
    }

    // 从用户信息中获取 userid
    const userId = userInfo.userid;

    // 调用后端接口获取收货地址列表
    reqAddressListByuserid(userId)
      .then(res => {
        console.log("API 响应:", res);
        if (res.code === 200) {
          const addresses = res.data.selectAddressByUserid || [];
          console.log("原始地址数据:", addresses);
          
          // 处理地址数据，转换为前端需要的格式
          const processedAddresses = addresses.map(address => {
            return {
              id: address.addressid,
              name: address.consignee,
              phone: address.phone,
              province: address.province,
              city: address.city,
              district: address.district,
              detail: address.address,
              distance:address.distance,
              duration:address.duration,
              cmorkm:address.cmorkm,
              isDefault: address.defaultaddress === 0 
            };
          });
          
          this.setData({
            addressList: processedAddresses
          });
        } else {
          throw new Error(res.msgerr || '加载收货地址失败');
        }
      })
      .catch(err => {
        console.error('加载收货地址失败:', err);
        wx.showToast({
          title: err.message || '加载收货地址失败',
          icon: 'none'
        });
      });
  },

  // 新增地址
  addAddress: function() {
    const then=this;
    wx.navigateTo({
      url: '/pages/addressEdit/addressEdit',
      events: {
        // 注册事件监听器
        backEvent: function(data) {
          console.log('收到数据：', data)
          //新增数据
          const address={
            name: data.name,
            phone: data.phone,
            province: data.province,
            city: data.city,
            district: data.district,
            detail: data.detail}
            let addressList=then.data.addressList
            if(address.name!=undefined){
              console.log("姓名："+address.name)
              addressList.push(address)
            }
          then.setData({ textData: data.obj,
            distance: data.distance ,
            duration:data.duration,
            addressList,
          mi:data.mi})
        }
      }
    });
  },

  // 编辑地址
  editAddress: function(e) {
    const addressid = e.currentTarget.dataset.id;
    console.log("这是编辑地址，addressid:", addressid);
    wx.navigateTo({
      url: '/pages/addressEdit/addressEdit?addressid=' + addressid
    });
  },

  // 删除地址
 // 删除地址
 deleteAddress: function(e) {
    if (this.data.deleting) return;
    
    const id = e.currentTarget.dataset.id;
    const that = this;
    
    wx.showModal({
      title: '提示',
      content: '确定要删除该收货地址吗？',
      success(res) {
        if (res.confirm) {
          that.confirmDeleteAddress(id)
        }
      }
    });
  },

  confirmDeleteAddress: function(addressid) { 
    return DeleteByaddressid(addressid)
      .then(res => {
        if (res === 1) {
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          });
          // 更新本地列表
          this.setData({
            addressList: this.data.addressList.filter(item => item.id !== addressid)
          });
        } else {
          throw new Error(res.msgerr || '删除地址失败');
        }
      })
      .catch(err => {
        console.error('删除失败:', err);
        wx.showToast({
          title: err.message.includes('network') ? '网络错误' : '删除失败',
          icon: 'none'
        });
        // 刷新列表恢复状态
        this.getAddressList();
      })
      .finally(() => {
        wx.hideLoading();
      });
  }
});